<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="文件名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="存储类型" prop="storageType">
        <el-select v-model="queryParams.storageType" placeholder="请选择存储类型" clearable size="small">
          <el-option
            v-for="item in storageTypeList"
             :key="item.value"
             :label="item.name"
             :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tool:file:edit']"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-refresh"
          size="mini"
          @click="handleSync"
          :loading="syncLoading"
          v-hasPermi="['tool:file:edit']"
        >同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-s-tools"
          size="mini"
          @click="handleConfig"
          v-hasPermi="['tool:file:edit']"
        >配置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tool:file:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tool:file:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="55"  />
      <el-table-column  label="文件名" align="center" prop="name" >
        <template slot-scope="scope">
          <el-popover
            :content="scope.row.realName"
            placement="top-start"
            title="路径"
            width="200"
            trigger="hover"
          >
            <a
              slot="reference"
              :href="scope.row.path"
              class="el-link--primary"
              style="word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;"
              target="_blank"
            >
              {{ scope.row.name }}
            </a>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="预览图" align="center" prop="path" >
        <template slot-scope="{row}">
          <el-image
            :src="row.path"
            :preview-src-list="[row.path]"
            fit="contain"
            lazy
            class="el-avatar"
          >
            <div slot="error">
              <i class="el-icon-document" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="文件类型" align="center" prop="suffix" />
      <el-table-column label="类别" align="center" prop="type" />
      <el-table-column label="大小" align="center" prop="size" />
      <el-table-column label="存储类型" align="center" prop="storageType" >
        <template slot-scope="{row}">
          <el-tag v-for="item in storageTypeList" v-if="item.value == row.storageType" :key="item.value" v-text="item.name" :type="item.type">标签一</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" >
        <template slot-scope="{row}">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件存储对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" append-to-body  width="600px" @close="handleSubmit">
      <el-upload
        :on-preview="handlePictureCardPreview"
        :before-remove="handleBeforeRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        :headers="headers"
        :file-list="fileList"
        :action="fileUploadApi"
        list-type="picture-card"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <el-dialog append-to-body :visible.sync="dialogVisible">
        <img :src="dialogImageUrl" width="100%" alt="">
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="存储配置" :visible.sync="configOpen" :close-on-click-modal="false" width="600px" @close="handleConfigCancel">
      <el-form ref="configForm" :model="configForm" :rules="configRules" label-width="100px">
        <el-form-item label="存储类型" prop="storageType">
          <el-radio-group v-model="configForm.storageType">
            <el-radio v-for="item in storageTypeList"
                      :key="item.value"
                      :label="item.value"
                      :value="item.value">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="configForm.storageType == '1'" label="accessKey" prop="accessKey">
          <el-input v-model="configForm.accessKey" placeholder="accessKey，在安全中心，秘钥管理中查看" />
        </el-form-item>
        <el-form-item v-if="configForm.storageType == '1'" label="secretKey" prop="secretKey">
          <el-input v-model="configForm.secretKey" placeholder="secretKey，在安全中心，秘钥管理中查看" />
        </el-form-item>
        <el-form-item v-if="configForm.storageType == '1'" label="空间名称" prop="bucket">
          <el-input v-model="configForm.bucket" placeholder="存储空间名称作为唯一的 Bucket 识别符" />
        </el-form-item>
        <el-form-item v-if="configForm.storageType == '1'" label="外链域名" prop="host">
          <el-input v-model="configForm.host" placeholder="外链域名，可自定义，需在七牛云绑定" />
        </el-form-item>
        <el-form-item v-if="configForm.storageType == '1'" label="存储区域" prop="zone">
          <el-select v-model="configForm.zone" placeholder="请选择存储区域">
            <el-option
              v-for="item in qiniuZones"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="configForm.storageType == '1'" label="空间类型" prop="type">
          <el-radio v-model="configForm.type" label="公开">公开</el-radio>
          <el-radio v-model="configForm.type" label="私有">私有</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleConfigSubmit">确 定</el-button>
        <el-button @click="handleConfigCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { listFile,  delFile, exportFile,sync } from "@/api/tool/file";
import { getToken } from "@/utils/auth";
import { setConfigKey } from "@/api/system/config";

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 文件存储表格数据
      dataList: [],
      fileList: [],
      pictures: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示配置
      configOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        suffix: undefined,
        path: undefined,
        type: undefined,
        size: undefined,
        storageType: undefined,
      },
      dialogImageUrl: '',
      dialogVisible: false,
      syncLoading: false,
      headers: { Authorization: "Bearer " + getToken() },
      storageTypeList: [
        {value: '0', name: '本地',type: 'info'},
        {value: '1', name: '七牛云',type: 'success'},
        {value: '2', name: '阿里云',type: 'success'},
        {value: '3', name: '腾讯云',type: 'success'},
      ],
      configForm: {
        configId: null,
        storageType: null,
        accessKey: null,
        secretKey: null,
        bucket: null,
        host: null,
        zone: null
      },
      configRules: {
        accessKey: [
          { required: true, message: "请输入accessKey", trigger: "blur" }
        ],
        secretKey: [
          { required: true, message: "请输入secretKey", trigger: "blur" }
        ],
        bucket: [
          { required: true, message: "请输入空间名称", trigger: "blur" }
        ],
        host: [
          { required: true, message: "请输入外链域名", trigger: "blur" }
        ],
        zone: [
          { required: true, message: "请选择存储区域", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择空间类型", trigger: "blur" }
        ]
      },
      qiniuZones: ['华东', '华北', '华南', '北美', '东南亚']
    };
  },
  computed: {
    ...mapGetters([
      'fileUploadApi'
    ])
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文件存储列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleConfigCancel(){
      this.configOpen = false;
    },
    // 表单重置
    reset() {
      this.fileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "文件上传";
    },
    handleSync(){
      this.syncLoading = true;
      sync().then(response => {
        this.msgSuccess("同步成功");
        this.getList();
        this.syncLoading = false;
      }).catch(err => {
        this.syncLoading = false;
      });
    },
    /** 提交按钮 */
    handleSubmit: function() {
      this.fileList = [];
      this.dialogVisible = false;
      this.dialogImageUrl = '';
      this.open = false;
      this.getList();
    },
    handleConfigSubmit: function(){
      this.$refs["configForm"].validate(valid => {
        if(valid){
          setConfigKey('sys.file.config',JSON.stringify(this.configForm)).then(response => {
            this.msgSuccess("更新配置信息");
            this.configOpen = false;
          });
        }
      });
    },
    handleConfig: function(){
      this.getConfigKey("sys.file.config").then(response => {
        this.configForm = JSON.parse(response.data);
        this.configOpen = true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$confirm('是否确认删除文件存储编号为"' + fileIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFile(fileIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有文件存储数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportFile(queryParams);
        }).then(response => {
          this.download(response.data);
        }).catch(function() {});
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleBeforeRemove(file, fileList) {
      for (let i = 0; i < this.pictures.length; i++) {
        if (this.pictures[i].uid === file.uid) {
          delFile(this.pictures[i].fileId);
          return true
        }
      }
    },
    handleSuccess(response, file, fileList) {
      const uid = file.uid;
      const fileId = response.data.fileId;
      this.pictures.push({ uid, fileId });
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message);
      this.msgError(msg.message);
    },
  }
};
</script>
